define([], function() {
	return{
		title:['<a href="user.html">个人中心</a>', "商城管理", "商品管理"],
		init:function(content){
			//UE.getEditor('newsContent');
			//UE.getEditor('newsContent2');
			let form = content.children("form");
			let table = content.children("table");
			let search = [];
			let productClassId = content.find("select[name='productClassId']");
			let productTemplate = content.find("._productTemplate");
			let deleteModal = $("#deleteModal");
			let imgs = $("._imgs");
			var modal = content.find("#modal1");
			
			let productAdd = $("#productAdd");
			let productUpdate = $("#productUpdate");
			
			
			productUpdate.find("._img").on("click", function() {
				$(this).prev().trigger("click");
				return false;
			});
			
			var imgFile = productUpdate.find(":file[name='img']");
			var img = $("#imgShow");
			
			imgFile.on("change", function() {
				var f = imgFile[0].files[0];
				console.info(f);
				var reader = new FileReader();
				reader.onload = function() {
					//		alert("aa");
					img[0].src = reader.result;
				}
				reader.readAsDataURL(f);
			});
			
			productUpdate.on("reset", function() {
				img[0].src = "img/_noimg.png";
			});
			
			
			
			var progress = $(".progress");
			productUpdate.on("submit",function(){
				let formData = new FormData(productUpdate[0]);
				progress.show();
				$.ajax({
					type: "post",
					url: "shop/product-update.do",
					processData: false, // 不会将 data 参数序列化字符串
					contentType: false, // 根据表单 input 提交的数据使用其默认的 contentType
					data: formData,
					success: function(data) {
						if(data.ok) {
							toastr.success("修改成功");
							$("#modal1").modal('hide');
							productUpdate.trigger("reset");
						} else {
							toastr.error(data.message);
						}
						progress.hide();
					},
					dataType: "json",
					xhr: function() {
						var xhr = new window.XMLHttpRequest();
						xhr.upload.addEventListener("progress", function(evt) {
							if(evt.lengthComputable) {
								var percentComplete = evt.loaded * 100 / evt.total;
								progress.children().css("width", percentComplete + "%");
							}
						}, false);
						return xhr;
					}
				});
				return false;
			});
			
			
			productAdd.find("._img").on("click", function() {
				$(this).prev().trigger("click");
				return false;
			});
			
			var imgFile2 = productAdd.find(":file[name='img']");
			var img2 = $("#imgShow2");
			
			imgFile2.on("change", function() {
				var f = imgFile2[0].files[0];
				console.info(f);
				var reader = new FileReader();
				reader.onload = function() {
					//		alert("aa");
					img2[0].src = reader.result;
				}
				reader.readAsDataURL(f);
			});
			
			productAdd.on("reset", function() {
				img2[0].src = "img/_noimg.png";
			});
			
			var progress2 = $(".progress2");
			productAdd.on("submit",function(){
				progress2.show();
				 //获取文件对象,files
                //是文件选取控件的属性,
                //存储的是文件选取控件选取的文件对象,类型是一个数组
				let formData = new FormData(productAdd[0]);
				
        		//创建formdata对象,
        		//formData用来存储表单的数据，
        		//表单数据时以键值对形式存储的。
        		
                //formData.append("file",$("#img3")[0]);
                //console.info(formData);
                
                $.ajax({
                	url:"shop/add-product.do",
                	type:"post",
                	processData: false, //必须false才会避开jQuery对 formdata 的默认处理  不会将 data 参数序列化字符串
            		contentType: false, //必须false才会自动加上正确的Content-Type  根据表单 input 提交的数据使用其默认的 contentType
            		data: formData,
            		success: function(data) {
            			if(data.ok) {
            				toastr.success("上传成功");
            				$("#modal2").modal('hide');
            				productAdd.trigger("reset");
            			} else {
            				toastr.error(data.message);
            			}
            			progress.hide();
            		},
            		dataType: "json",
					xhr: function() {
						var xhr = new window.XMLHttpRequest();
						xhr.upload.addEventListener("progress2", function(evt) {
							if(evt.lengthComputable) {
								var percentComplete = evt.loaded * 100 / evt.total;
								progress.children().css("width", percentComplete + "%");
							}
						}, false);
						return xhr;
					}
				});
				return false;
				
			});
			
			
			
			let showQuery = function(data) {
				$("#productId").val(data.productId);
				$("#productName").val(data.productName);
				$("#productManager").val(data.productManager);
				$("#productInventory").val(data.productInventory);
				$("#productPrice1").val(data.productPrice1);
				$("#productPrice2").val(data.productPrice2);
				$("#productColors").val(data.productColors);
				$("#productTime").val(data.productTime);
				$("#productSales").val(data.productSales);
				$("#productIp").val(data.productIp);
				//$("#newsContent").val(data.productContent);
				$("#imgShow")[0].src = data.productImgs;
				//$("#_imgs").html('<img src='+ data.productImgs +' alt="140x140" style="width: 140px; height: 140px;" class="img-rounded" >');
				//alert(data.productContent);
				modal.modal('show');
			}
			
			let tableInit = function(){
				let actionEvent = {
						"click .temp2": function(e, value, row) {
							if(!window.confirm('是否删除商品')){
								return false;
							}
							$.post(
									"shop/delete.do", {
										"productId": row.productId,
									},
									function(data) {
										if(data.ok) {
											table.bootstrapTable('refresh');
											toastr.success("删除成功");
										} else {
											toastr.error("设置锁定状态失败：" + data.message);
										}
									}, "json"
								);
						},
						"click .temp1": function(e, value, row) {
							$.ajax({
								url:"shop/modify-product-list.do",
								async:true,
								type:"POST",
								data:{
									"productId" : row.productId
								},
								// 成功后开启模态框
						        success : showQuery,
						        error : function() {
						        	toastr.error("设置锁定状态失败：" + data.message);
						        },
						        dataType : "json"
								
							});
						},
						"change .productOut": function(e, value, row) {
							e.target.disabled = true;
							$.post(
								"shop/modify.do", {
									"productId": row.productId,
									"productOut": e.target.checked
								},
								function(data) {
									e.target.disabled = false;
									if(data.ok) {
										toastr.success("上下架成功");
									} else {
										toastr.error("上下架失败：" + data.message);
									}
								}, "json"
							);
						},
						"change .productClassId": function(e, value, row) {
							e.target.disabled = true;
							$.post(
								"shop/product-class-modify.s", {
									"productId": row.productId,
									"productClassId": e.target.value
								},
								function(data) {
									e.target.disabled = false;
									if(data.ok) {
										toastr.success("修改商品类别成功");
									} else {
										toastr.error("修改商品类别失败：" + data.message);
									}
								}, "json"
							);
						},
						"click .temp": function(e, value, row) {}
				};
				table.bootstrapTable({
					
					url:'shop/product-page-ajax.s', // 表格数据来源
					method:"get",
					sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
					pageNumber: 1, //初始化加载第一页，默认第一页
					pageSize: 10, //每页的记录行数（*）
					pageList: [5, 10, 15, 20, 30, 50], //可供选择的每页的行数（*）
					pagination: true, //是否显示分页（*）
					dataField: "list",
					toolbar: form,
					queryParamsType: "",
					queryParams: function(p) {
						let ps = [].concat(search);
						ps.push({
							"name": "current",
							"value": p.pageNumber
						});
						ps.push({
							"name": "rowMax",
							"value": p.pageSize
						});
						ps.push({
							"name": "sortName",
							"value": p.sortName
						});
						ps.push({
							"name": "sortOrder",
							"value": p.sortOrder
						});
						return ps;
					},
					columns:[{
						field: 'productId',
						title: '产品编号',
						sortable: true,
						sortName: "PRODUCT_ID",
						width: 100
					},{
						field: 'productName',
						title: '产品名称',
						align: "center",
						sortable: true,
						sortName: "PRODUCT_NAME",
						width: 100
					},{
						field: 'productPrice1',
						title: '市场价',
						align: "center",
						sortable: true,
						sortName: "PRODUCT_PRICE_1",
						width: 40
					},{
						field: 'productSales',
						title: '销量',
						align: "center",
						sortable: true,
						sortName: "PRODUCT_SALES",
						width: 40
					},{
						field: 'productInventory',
						title: '库存',
						align: "center",
						sortable: true,
						sortName: "PRODUCT_INVENTORY",
						width: 40
					},{
						field: 'productCreateTime',
						title: '产品创建时间',
						align: "center",
						sortable: true,
						sortName: "PRODUCT_CREATE_TIME",
						width: 100
					},{
						field: 'productOut',
						align: "center",
						title: '是否下架',
						width: 40,
						events: actionEvent,
						formatter: function(value, row, index, field) {
							if(value) {
								return "<input class='productOut' type='checkbox' checked='checked' />";
							}
							return "<input class='productOut' type='checkbox' />";
						}
					}, {
						field: 'productClassId',
						align: "center",
						title: '商品类别',
						width: 120,
						events: actionEvent,
						formatter: function(value, row, index, field) {
							let s = productTemplate.children("select");
							s.children().removeAttr("selected").filter("[value='" + value + "']").attr("selected", "selected");
							return productTemplate.html();
						}
					}, {
						field: 'temp1',
						align: "center",
						title: '修改商品',
						width: 100,
						events: actionEvent,
						formatter: function(value, row, index, field) {
							return '<a class="temp1" href="javascript:void(0);">修改商品</a>';
						}
					}, {
						field: 'temp2',
						align: "center",
						title: '删除商品',
						width: 100,
						events: actionEvent,
						formatter: function(value, row, index, field) {
							return '<a class="temp2" href="javascript:void(0); ">删除商品</a>';
						}
					}]
				});
			};
			form.on("submit",function(){
				search = form.serializeArray();
				table.bootstrapTable('refresh');
				return false;
			});
			$.get(
				"shop/product-class-list.s", 
				function(data) {
					$.each(data, function(i,itme) {
						$("<option></option>").text(itme.productClassName).val(itme.productClassId).appendTo(productClassId);
					});
					tableInit();
				},"json"
			);
		}
	}
});